﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using AutoFacUtils;
using FluentValidation;
using CashFlow.Web.Models.Order;
using CashFlow.Web.Service;
using CashFlow.Web.Common;
using CashFlow.Web.Def;

namespace CashFlow.Web.Validator.Order
{
    public class UploadPaymentVoucherModelValidator
        : AbstractValidator<UploadPaymentVoucherModel>
    {
        private IUserService GetUserService() { return AutoFacHelper.Get<IUserService>(); }
        private IOrderService GetOrderService() { return AutoFacHelper.Get<IOrderService>(); }

        public UploadPaymentVoucherModelValidator()
        {
            CascadeMode = CascadeMode.Stop;
            RuleFor(x => x.file).Must(x => CommonValidator.IsLegalUploadFile(x))
                .WithMessage("非法UploadFile");
            RuleFor(x => x.OrderId).Must((x, y) => IsOrderIdValiad(x))
                .WithMessage("非法OrderId & SellerUserId");
        }

        private bool IsOrderIdValiad(UploadPaymentVoucherModel model)
        {
            var date = MyCommonTool.GetOrderDate();
            var userService = GetUserService();
            var ui = userService.GetLoginUser();
            var orderService = GetOrderService();
            var n = orderService.Count(
                        x => x.Id == model.OrderId
                        && x.CreateTime.ToString("yyyy-MM-dd") == date
                        && x.BuyerUserId == ui.Id
                        && x.SellerUserId == model.SellerUserId
                        && x.State == (int)EOrderState.NotPaied
                    );
            return n > 0;
        }
    }
}